import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import request from '@/core/request'
const user = {
  state: {
    hasSetInfo: false,
    token: '',
    id: '0',
    avatar: 'https://gw.alipayobjects.com/zos/antfincdn/XAosXuNZyF/BiazfanxmamNRoxxVxka.png',
    username: '',
    name: ''
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_INFO: (state, info) => {
      state.id = info.id
      state.username = info.username
      state.name = info.name
      state.avatar = process.env.VUE_APP_MINIO_URL + info.head
      state.hasSetInfo = true
    }
  },

  actions: {
    // 登录
    login ({ commit }, param) {
      return request.post('/zg-system/un/token/create', param, data => {
        storage.set(ACCESS_TOKEN, data, 7 * 24 * 60 * 60 * 1000)
        commit('SET_TOKEN', data)
      })
    },

    // 获取用户信息
    getInfo ({ commit }) {
      return request.get('/zg-system/user/info', {}, data => {
        commit('SET_INFO', data)
      })
    },

    // 设置token
    setToken ({ commit }, token) {
      commit('SET_TOKEN', token)
    },

    // 登出
    logout ({ commit, state }) {
      /*
      return new Promise((resolve) => {
        commit('SET_TOKEN', '')
        storage.remove(ACCESS_TOKEN)
        resolve()
      }) */
      return request.post('/zg-system/token/remove', {}, () => {
        commit('SET_TOKEN', '')
        storage.remove(ACCESS_TOKEN)
      })
    }
  }
}

export default user
